package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.model.comment.dtos.ApCommentDto;
import com.heima.model.comment.dtos.CommentAllVo;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.CommentGetListDto;
import com.heima.model.wemedia.dtos.ManageDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.utils.AppThreadLocalUtils;
import com.heima.model.wemedia.utils.WmThreadLocalUtils;
import com.heima.wemedia.service.ManageService;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WmUserService wmUserService;
    /**
     * 获取文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult getNewsList(ManageDto dto) {

        //获取当前登录对象
        WmUser user = WmThreadLocalUtils.getUser();
        Integer userId = user.getId();
        dto.setUserId(userId);

        //通过feign远程调用,获取文章信息
        PageResponseResult pageResponseResult = articleClient.getNewsList(dto);

        return pageResponseResult;
    }

    /**
     * 打开或关闭评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateCommentStatus(ApCommentDto dto) {
        if (dto.getArticleId()==null || dto.getOperation() ==null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        int start;
        if (dto.getOperation() == 0){
            //关闭评论
            start = 0;

            //删除对应文章下所有的评论
            List<ApComment> apComments = mongoTemplate
                    .find(Query.query(Criteria.where("entryId").is(dto.getArticleId())), ApComment.class);
            for (ApComment apComment : apComments) {
                List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(apComment.getId())), ApCommentRepay.class);
                List<ApCommentLike> apCommentLikes1 = mongoTemplate.find(Query.query(Criteria.where("commentId").is(apComment.getId())), ApCommentLike.class);
                for (ApCommentRepay apCommentRepay : apCommentRepays) {
                    List<ApCommentLike> apCommentLikes2 = mongoTemplate.find(Query.query(Criteria.where("commentId").is(apCommentRepay.getId())), ApCommentLike.class);
                    mongoTemplate.remove(apCommentRepay);
                    for (ApCommentLike apCommentLike2 : apCommentLikes2) {
                        mongoTemplate.remove(apCommentLike2);
                    }
                }
                mongoTemplate.remove(apComment);
                for (ApCommentLike apCommentLike1 : apCommentLikes1) {
                    mongoTemplate.remove(apCommentLike1);
                }
            }
        }else {
            //打开评论
            start = 1;
        }
        articleClient.getArticleConfig(dto.getArticleId(),start);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看评论
     *
     * @param dto
     */
    @Override
    public ResponseResult getList(CommentGetListDto dto) {
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        PageRequest page = PageRequest.of(dto.getPage()-1,dto.getSize());

//        List<ApComment> entryId = mongoTemplate
//                .find(Query.query(Criteria.where("entryId").is(dto.getArticleId())).with(page), ApComment.class)
//                .stream().sorted(Comparator.comparing(ApComment::getCreatedTime).reversed())
//                .collect(Collectors.toList());
        List<ApComment> apComments = mongoTemplate
                .find(Query.query(Criteria.where("entryId").is(dto.getArticleId())).with(page), ApComment.class)
                .stream().sorted(Comparator.comparing(ApComment::getCreatedTime).reversed())
                .collect(Collectors.toList());

        List<CommentAllVo> commentAllVoList = new ArrayList<>();
        for (ApComment apComment : apComments) {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apComment,apCommentRepayVo);
            Criteria criteria = new Criteria();
            criteria.andOperator(
                    Criteria.where("commentId").is(apComment.getId()),
                    Criteria.where("authorId").is(WmThreadLocalUtils.getUser().getId())
            );
            if (mongoTemplate.exists(Query.query(criteria),ApCommentLike.class)){
                apCommentRepayVo.setOperation(0);
            }

            CommentAllVo commentAllVo = new CommentAllVo();
            commentAllVo.setApComments(apCommentRepayVo);
            List<ApCommentRepay> commentId = mongoTemplate.find(Query.query(Criteria.where("commentId").is(apComment.getId())), ApCommentRepay.class);
            commentAllVo.setApCommentRepays(commentId);
            commentAllVoList.add(commentAllVo);
        }


        return ResponseResult.okResult(commentAllVoList);
    }

    /**
     * 作者回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authorSave(ApCommentDto dto) {
        if (dto.getCommentId() == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer userId = WmThreadLocalUtils.getUser().getId();

        //获取作者名称
        WmUser wmUser = wmUserService.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId, userId));
        String userName = wmUser.getName();

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(userId);
        apCommentRepay.setAuthorName(userName);
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdateTime(new Date());
        mongoTemplate.save(apCommentRepay);
        return ResponseResult.okResult("回复成功");
    }

    /**
     * 作者点赞或取消点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authLike(ApCommentDto dto) {
        if (dto.getCommentId()==null||dto.getOperation()==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ApComment.class);
        Integer likes = apComment.getLikes();

        if (dto.getOperation()==0){
            //点赞
            likes = likes+1;

            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setAuthorId(WmThreadLocalUtils.getUser().getId());
            mongoTemplate.save(apCommentLike);
        }else {
            //取消赞
            if (likes>0){
                likes=likes-1;
            }
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(dto.getCommentId())),ApCommentLike.class);
        }
        Update update = new Update();
        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(dto.getCommentId())),update.set("likes",likes),ApComment.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
